<?php
class ManageController extends Zend_Controller_Action
{
    /**
     * 进入控制器的时候查看客户端是否存在cookie
     * 如果存在验证通过直接分配session
     * 否则走到客户端指定的控制器
     * @see Zend_Controller_Action::init()
     */
    public function init()
    {
    	parent::init();

    	$actionName = $this->_request->getActionName();
    	$notCheck = array('index', 'login', 'logout');
        $cookieName = Zend_Registry::get('database')->admin->cookie;
        if (isset($_COOKIE[$cookieName])) {
            $authObj = new Business_Manage_Auth();
            $cookieResult = $authObj->validateAuthSignature(
                $_COOKIE[$cookieName]
            );
            if ($cookieResult['errorcode'] == 0) {
                $authObj->setUserLogin($cookieResult['result']);
            }
        }
        if (!in_array($actionName, $notCheck)) {
        	$authObj = new Business_Manage_Auth();
        	if (!$authObj->isLogin()) {
        		$this->_redirect('/manage/index');
        	}
        }
    }

    /**
     * 管理员登陆界面
     * 如果登陆直接进入homepage管理页
     */
    public function indexAction()
    {
        $this->view->title = '管理员登录';
        $authObj = new Business_Manage_Auth();
        if ($authObj->isLogin()) {
            $this->_redirect('/manage/homepage');
        }
    }

    public function aboutAction()
    {
        $request = $this->_request->getParams();
        $language = $this->_request->getParam('language', 'zh');
        $classType = $request['action'];
        $this->_dealPages($classType, $language);
        $this->render('page');
    }

    public function contactAction()
    {
        $request = $this->_request->getParams();
        $language = $this->_request->getParam('language', 'zh');
        $classType = $request['action'];
        $this->_dealPages($classType, $language);
        $this->render('page');
    }

    /**
     * 用户登陆验证action
     * 如果用户名密码正确直接分配session
     * 如果有选择记住我，就分配cookie
     * 成功之后跳转到homepage管理页
     */
    public function loginAction()
    {
        $username = $this->_request->getParam('username');
        $password = $this->_request->getParam('password');
        $rememberme = $this->_request->getParam('rememberme');
        if (isset($username) && isset($password) && $username != "" &&
         $password != "") {
            $authObj = new Business_Manage_Auth();
            $authResult = $authObj->checkLogin($username, $password);
            if ($authResult['errorcode'] == 0) {
                if (isset($rememberme)) {
                    $cookieName = Zend_Registry::get('database')->admin->cookie;
                    $cookie = $authObj->generateAuthSignature(
                        $authResult['result'],
                        $authObj->getCookieExpireTime()
                    );
                    setcookie(
                        $cookieName,
                        $cookie,
                        $authObj->getCookieExpireTime()
                    );
                }
                $authObj->setUserLogin($authResult['result']);
                $this->_redirect('/manage/homepage');
            } else {
                $this->view->errormsg = '<div id="login_error">登录失败！</div>';
                $this->render('index');
            }
        } else {
            $this->view->errormsg = '<div id="login_error">登录失败！</div>';
            $this->render('index');
        }
    }

    /**
     * 所有文章列表
     */
    public function modelListAction()
    {
    	$view = $this->view;
    	$view->title = 'Admin - 模特列表管理';
    	$view->level1 = 'model';
    	$view->level2 = 'list';
    	$view->page = $page = $this->_request->getParam('page', 1);
    	$view->rowCount = $rowCount = 10;
    	$foreignType = Zend_Registry::get('config')->model->type->foreign;
    	$foreignAmount = Business_Model::getInstance()->getModelAmount($foreignType);
    	$otherType = Zend_Registry::get('config')->model->type->other;
    	$otherAmount = Business_Model::getInstance()->getModelAmount($otherType);
    	$amount = $foreignAmount + $otherAmount;
    	$view->total = $total = ceil($amount / $rowCount);
    	//页码超过范围处理
    	if ($page < 1) {
    		$view->page = $page = 1;
    	}
    	if ($page > $total) {
    		$view->page = $page = $total;
    	}
    	$types = array($foreignType, $otherType);
    	$modelList = Business_Model::getInstance()->getModelList($types, 0, $page, $rowCount);
    	$view->modelList = $modelList;
    	$view->modelType = Business_Model::getInstance()->getModelTypes();
    }

    public function deleteModelAction()
    {
    	$view = $this->view;
    	$id = $this->_request->getParam('id', 0);
    	$result = Business_Model::getInstance()->delete($id);
    	$this->_redirect('/manage/model-list');
    }

    public function deleteModelLifeAction()
    {
        $view = $this->view;
        $id = $this->_request->getParam('id', 0);
        $result = Business_Model::getInstance()->delete($id);
        $this->_redirect('/manage/models-life');
    }

    public function deleteModelJoinAction()
    {
        $view = $this->view;
        $id = $this->_request->getParam('id', 0);
        $result = Business_Model::getInstance()->deleteModelJoin($id);
        $this->_redirect('/manage/model-join');
    }

    /**
     * 发布模特页面
     * 包括登陆验证
     */
    public function editModelAction()
    {
    	$view = $this->view;
    	$view->title = 'Admin - Edit Article';
        $authObj = new Business_Manage_Auth();
        $authResult = $authObj->validateAuthSignature();
        if ($authObj->isLogin()) {
            if ($this->_request->getPost('submit')) {
                //接收提交的信息
                $modelInfo = array();
                $tabeInfo = Zend_Registry::get('database')->modellist;
                $modelInfo[$tabeInfo->id] = $this->_request->getParam($tabeInfo->id, 0);
                $modelInfo[$tabeInfo->name] = $this->_request->getParam($tabeInfo->name, '');
                $modelInfo[$tabeInfo->description1] = $this->_request->getParam($tabeInfo->description1, '');
                $modelInfo[$tabeInfo->description2] = $this->_request->getParam($tabeInfo->description2, '');
                $modelInfo[$tabeInfo->description3] = $this->_request->getParam($tabeInfo->description3, '');
                if (ini_get('magic_quotes_gpc')) {
                    $modelInfo[$tabeInfo->description1] = stripslashes($modelInfo[$tabeInfo->description1]);
                    $modelInfo[$tabeInfo->description2] = stripslashes($modelInfo[$tabeInfo->description2]);
                    $modelInfo[$tabeInfo->description3] = stripslashes($modelInfo[$tabeInfo->description3]);
                }
                $modelInfo[$tabeInfo->coverimage] = $this->_request->getParam($tabeInfo->coverimage, '0');
                $modelInfo[$tabeInfo->type] = $this->_request->getParam($tabeInfo->type, 1);
                $modelInfo[$tabeInfo->display] = $this->_request->getParam($tabeInfo->display, 0);
                if (!empty($modelInfo[$tabeInfo->display])) {
                    $modelInfo[$tabeInfo->display] = 1;
                }
                if ($modelInfo[$tabeInfo->id] == 0) {
                    //添加操作
                    $pictures = $_FILES['pictures']['name'];
                    $pictures = $this->_decoratePictures($pictures);
                    if (!empty($pictures)) {
                        $addresses = $_FILES['pictures']['tmp_name'];
                        $rtn = $this->_dealModelPictures($modelInfo, $pictures, $addresses);
                    } else {
                        $rtn = array(
                            'errorcode' => -1,
                            'errormsg' => '请上传照片'
                        );
                    }
                } else {
                    //修改操作
                    //操作封面
                    $existpics = $this->_request->getParam('existpics');
                    $modelInfo[$tabeInfo->pictures] = $existpics;
                    if (!is_int($modelInfo[$tabeInfo->coverimage])) {
                        if (!empty($existpics)) {
                            $count = 0;
                            foreach ($existpics as $existpic) {
                                if ($existpic == $modelInfo[$tabeInfo->coverimage]) {
                                    $modelInfo[$tabeInfo->coverimage] = $count;
                                    break;
                                }
                                $count++;
                            }
                        }
                    } else {
                        $count = count($existpics);
                        $modelInfo[$tabeInfo->coverimage] += $count;
                    }

                    $pictures = $_FILES['pictures']['name'];
                    $pictures = $this->_decoratePictures($pictures);
                    if (!empty($pictures)) {
                        //如果有新上传的图片
                        $addresses = $_FILES['pictures']['tmp_name'];
                        $rtn = $this->_dealModelPictures($modelInfo, $pictures, $addresses);
                    } else {
                        //没有新上传的图片就更新原来的
                        $rtn = $this->_saveModelInfo($modelInfo);
                    }
                }
                $this->view->result = $rtn;
                $this->_editModel();
                $this->render('edit-model');
            } else {
                $this->view->result = array();
                $this->_editModel();
            }
        } else {
            $this->_redirect('/manage');
        }
    }

    public function modelsLifeAction()
    {
        $view = $this->view;
        $view->title = 'Admin - 模特生活管理';
        $view->level1 = 'model';
        $view->level2 = 'life';
        $view->page = $page = $this->_request->getParam('page', 1);
        $view->rowCount = $rowCount = 10;
        $lifeType = Zend_Registry::get('config')->model->type->life;
        $amount = Business_Model::getInstance()->getModelAmount($lifeType);
        $view->total = $total = ceil($amount / $rowCount);
        //页码超过范围处理
        if ($page < 1) {
            $view->page = $page = 1;
        }
        if ($page > $total) {
            $view->page = $page = $total;
        }
        $modelList = Business_Model::getInstance()->getModelList(3, 0, $page, $rowCount);
        $view->modelList = $modelList;
        $view->modelType = Business_Model::getInstance()->getModelTypes();
    }

    /**
     * 发布模特生活页面
     * 包括登陆验证
     */
    public function editModelsLifeAction()
    {
        $view = $this->view;
        $authObj = new Business_Manage_Auth();
        $authResult = $authObj->validateAuthSignature();
        if ($authObj->isLogin()) {
            if ($this->_request->getPost('submit')) {
                //接收提交的信息
                $modelInfo = array();
                $tabeInfo = Zend_Registry::get('database')->modellist;
                $modelInfo[$tabeInfo->id] = $this->_request->getParam($tabeInfo->id, 0);
                $modelInfo[$tabeInfo->name] = $this->_request->getParam($tabeInfo->name, '');
                $modelInfo[$tabeInfo->description1] = $this->_request->getParam($tabeInfo->description1, '');
                $modelInfo[$tabeInfo->description2] = $this->_request->getParam($tabeInfo->description2, '');
                $modelInfo[$tabeInfo->description3] = $this->_request->getParam($tabeInfo->description3, '');
                $modelInfo[$tabeInfo->coverimage] = $this->_request->getParam($tabeInfo->coverimage, 0);
                $modelInfo[$tabeInfo->type] = $this->_request->getParam($tabeInfo->type, 1);
                $modelInfo[$tabeInfo->display] = $this->_request->getParam($tabeInfo->display, 0);
                if (!empty($modelInfo[$tabeInfo->display])) {
                    $modelInfo[$tabeInfo->display] = 1;
                }

                if ($modelInfo[$tabeInfo->id] == 0) {
                    //添加操作
                    $pictures = $_FILES['pictures']['name'];
                    if ($this->_checkPictures($pictures)) {
                        $addresses = $_FILES['pictures']['tmp_name'];
                        $rtn = $this->_dealModelPictures($modelInfo, $pictures, $addresses);
                    } else {
                        $rtn = array(
                            'errorcode' => -1,
                            'errormsg' => '请上传照片'
                        );
                    }
                } else {
                    //修改操作
                    $pictures = $_FILES['pictures']['name'];
                    if ($this->_checkPictures($pictures)) {
                        $addresses = $_FILES['pictures']['tmp_name'];
                        $rtn = $this->_dealModelPictures($modelInfo, $pictures, $addresses);
                    } else {
                    	$existpics = $this->_request->getParam('existpics');
                    	$modelInfo[$tabeInfo->pictures] = $existpics;
                        $rtn = $this->_saveModelInfo($modelInfo);
                    }
                }
                $this->view->result = $rtn;
                $this->_editModelsLife();
                $this->render('edit-models-life');
            } else {
                $this->view->result = array();
                $this->_editModelsLife();
            }
        } else {
            $this->_redirect('/manage');
        }
    }

    /**
     * homepage管理页面
     * 包括登陆验证
     */
    public function homepageAction()
    {
    	$view = $this->view;
    	$view->level1 = 'page';
    	$view->level2 = 'home';

        $authObj = new Business_Manage_Auth();
        if ($authObj->isLogin()) {
            $view->title = 'seemodel管理网站首页';
            $homepageObj = new Business_Manage_Homepage();
            list($slider, $sliderTable) = $homepageObj->getSliders();
            $view->slider = $slider;
            $view->sliderTable = $sliderTable;
        } else {
            $this->_redirect('/manage');
        }
    }

    /**
     * 用户退出action
     * 退出之后跳转到首页
     */
    public function logoutAction()
    {
        $authObj = new Business_Manage_Auth();
        $authObj->logout();
        $authObj->deleteCookie();
        $this->_redirect('/manage');
    }

    /**
     * 修改首页slider信息的action
     */
    public function modHomepageSliderAction()
    {
        $view = $this->view;
        $view->level1 = 'page';
        $view->level2 = 'home';

        $form = $this->_request->getParams();
        unset($form['controller']);
        unset($form['action']);
        unset($form['module']);
        $homepageObj = new Business_Manage_Homepage();
        $tableMaps = $homepageObj->getHomepageSliderTableInfo();
        $amount = count($form);
        $content = array();
        for ($i = 1; $i <= $amount / 4; $i++) {
            if ($form['imageUrl' . $i] != null) {
                $content[] = array(
                    $tableMaps->title => $form['title' . $i],
                    $tableMaps->description => $form['description' . $i],
                    $tableMaps->detailUrl => $form['detailUrl' . $i],
                    $tableMaps->imageUrl => $form['imageUrl' . $i]
                );
            }
        }
        if (count($content) != 0) {
            $rtn = $homepageObj->updateHomepageSlider($content);
            $this->view->errormsg = $rtn['errormsg'];
        } else {
            $this->view->errormsg = 'Nothing submitted!';
        }
        list($slider, $sliderTable) = $homepageObj->getSliders();
        $this->view->slider = $slider;
        $this->view->sliderTable = $sliderTable;
        $this->render('homepage');
    }

    public function modelJoinAction()
    {
    	$view = $this->view;
    	$view->title = 'Admin - 查看模特加盟';
    	$view->level1 = 'model';
    	$view->level2 = 'join';
    	$view->page = $page = $this->_request->getParam('page', 1);
    	$view->rowCount = $rowCount = 10;
    	$amount = Business_Model::getInstance()->getModelJoinAmount();
    	$view->total = $total = ceil($amount / $rowCount);
    	//页码超过范围处理
    	if ($page < 1) {
    		$view->page = $page = 1;
    	}
    	if ($page > $total) {
    		$view->page = $page = $total;
    	}
    	$modelList = Business_Model::getInstance()->getModelJoin($page, $rowCount);
    	$view->modelList = $modelList;
	}

	public function modelJoinDetailAction()
	{
	    $id = $this->_request->getParam('id');
	    if (empty($id)) {
	        $this->_redirect('/manage/model-join/');
	    } else {
	        $view = $this->view;
	        $view->title = 'Admin - 查看模特';
	        $view->level1 = 'model';
	        $view->level2 = 'join';
	        $joinTable = Zend_Registry::get('database')->modeljoin;
	        $path = APPLICATION_CONFIG_PATH . '/zh.ini';
	        $config = new Zend_Config_Ini($path, APPLICATION_ENV);
	        $registry = Zend_Registry::getInstance()->set('lang', $config);
	        $view->modelInfo = Business_Model::getInstance()->getModelJoinById($id);
	    }
	}

    public function compressCssAction()
    {
        //include global homepage style footer
        $files = Zend_Registry::get('config')->compress->css;
        $fileArr = explode(',', $files);
        $content = '';
        foreach ($fileArr as $file) {
            $filename = PROJECT_ROOT . CSS_MIN_PATH . $file;
            $content .= file_get_contents($filename);
        }
        echo $content;
        file_put_contents(PROJECT_ROOT . CSS_MIN_PATH . '/main.css', $content);
        exit;
    }

    protected function _dealPages($classType, $language)
    {
        $this->view->level1 = 'page';
        $this->view->level2 = $classType . '-' . $language;
        $this->view->language = $language;
        $pageTable = Zend_Registry::get('database')->page;
        $content = $this->_request->getPost($pageTable->content);
        if (ini_get('magic_quotes_gpc')) {
            $content = stripslashes($content);
        }
        $id = $this->_request->getPost($pageTable->id);
        $typeid = Zend_Registry::get('config')->page->$classType->id;
        $this->view->action = $classType;
        if (!empty($content) && !empty($language)) {
            $name = Zend_Registry::get('config')->page->$classType->name;
            $info = array(
                $pageTable->id => $id,
                $pageTable->mtime => date('c'),
                $pageTable->name => $name,
                $pageTable->content => $content,
                $pageTable->language => $language,
                $pageTable->typeid => $typeid
            );
            $result = Business_Page::getInstance()->savePage($info);
            if ($result["errorcode"] == 0) {
                $this->view->alert = $result["errormsg"];
            } else {
                $this->view->alert = $result["errormsg"];
            }
        } else {
            $this->view->alert = '';
        }
        $content = Business_Page::getInstance()->getAllPageInfoById($typeid, $language);
        $this->view->page = $content;
    }

    protected function _checkPictures($pictures)
    {
        $rtn = false;
        foreach ($pictures as $picture) {
            if (!empty($picture)) {
                $rtn = true;
            }
        }
        return $rtn;
    }

    protected function _decoratePictures($pictures)
    {
        $rtn = array();
        foreach ($pictures as $picture) {
            if (!empty($picture)) {
                $rtn[] = $picture;
            }
        }
        return $rtn;
    }

    protected function _dealModelPictures($modelInfo, $pictures, $addresses)
    {
        //检验所有的照片是否合法
        $switch = true;
        foreach ($pictures as $picture) {
            $type = array(
                "jpg",
                "gif",
                "jpeg",
                "png"
            );
            $tool = substr(strrchr($picture, '.'), 1);
            if (!in_array(strtolower($tool), $type)) {
                $rtn = array(
                    'errorcode' => -2,
                    'errormsg' => '您只能上传以下类型文件: jpg, gif, jpeg, png！'
                );
                $switch = false;
                break;
            }
        }
        //如果合法就保存
        if ($switch) {
            $tabeInfo = Zend_Registry::get('database')->modellist;
            $path = APPLICATION_PUBLIC_PATH . '/images/models/';
            $insertToDb = true;
            $pics = array();
            $len = count($pictures);
            for ($i = 0; $i < $len; $i++) {
                // 把上传的文件名以"."好为准做一个数组。
                $filename = explode(".", $pictures[$i]);
                // 取文件名，用时间戳
                $filename[0] = time() . '-' . ($i + 1);
                // 上传后的文件名
                $name = implode(".", $filename);
                $uploadfile = $path . $name;
                if (move_uploaded_file($addresses[$i], PROJECT_ROOT . $uploadfile)) {
                    //图片保存成功之后插入数据库
                    $modelInfo[$tabeInfo->pictures][] = $uploadfile;
                } else {
                    $rtn = array(
                        'errorcode' => -3,
                        'errormsg' => '保存图片失败'
                    );
                    $insertToDb = false;
                    break;
                }
            }
            if ($insertToDb) {
                $rtn = $this->_saveModelInfo($modelInfo);
            }
        }
        return $rtn;
    }

    protected function _saveModelInfo($modelInfo)
    {
        $tabeInfo = Zend_Registry::get('database')->modellist;
        //组成要插入数据库的数组
        $data = array(
            $tabeInfo->id => $modelInfo[$tabeInfo->id],
            $tabeInfo->name => $modelInfo[$tabeInfo->name],
            $tabeInfo->description1 => $modelInfo[$tabeInfo->description1],
        	$tabeInfo->description2 => $modelInfo[$tabeInfo->description2],
        	$tabeInfo->description3 => $modelInfo[$tabeInfo->description3],
            $tabeInfo->coverimage => $modelInfo[$tabeInfo->coverimage],
            $tabeInfo->type => $modelInfo[$tabeInfo->type],
            $tabeInfo->display => $modelInfo[$tabeInfo->display],
        );
        if (isset($modelInfo[$tabeInfo->pictures])) {
            $data[$tabeInfo->pictures] = serialize($modelInfo[$tabeInfo->pictures]);
        }
        //数据库操作
        $result = Business_Model::getInstance()->save($data);
        $rtn = array(
            'errorcode' => $result['errorcode'],
            'errormsg' => $result['errormsg']
        );
        return $rtn;
    }

    protected function _editModel()
    {
        $view = $this->view;
        $view->level1 = 'model';
        $view->level2 = 'list';
        $view->title = 'Admin - 编辑模特';
        $id = $this->_request->getParam('id', 0);
        $view->id = $id;
        //基本信息
        $view->modelType = Business_Model::getInstance()->getModelTypes();
        $modelDetail = Business_Model::getInstance()->getModelDetails($id);
        if (!$modelDetail) {
            $tabeInfo = Zend_Registry::get('database')->modellist;
            $modelDetail = array(
            				$tabeInfo->id => 0,
            				$tabeInfo->name => '',
            				$tabeInfo->description1 => '',
		            		$tabeInfo->description2 => '',
		            		$tabeInfo->description3 => '',
            				$tabeInfo->pictures => '',
            				$tabeInfo->coverimage => '',
            				$tabeInfo->type => 1,
            				$tabeInfo->display => 1,
            );
        }
        $view->model = $modelDetail;
    }

    protected function _editModelsLife()
    {
        $view = $this->view;
        $view->level1 = 'model';
        $view->level2 = 'life';
        $view->title = 'Admin - 编辑模特生活';
        $id = $this->_request->getParam('id', 0);
        $view->id = $id;
        //基本信息
        $view->modelType = Business_Model::getInstance()->getModelTypes();
        $modelDetail = Business_Model::getInstance()->getModelDetails($id);
        if (!$modelDetail) {
            $tabeInfo = Zend_Registry::get('database')->modellist;
            $modelDetail = array(
                $tabeInfo->id => 0,
                $tabeInfo->name => '',
                $tabeInfo->description1 => '',
            	$tabeInfo->description2 => '',
            	$tabeInfo->description3 => '',
                $tabeInfo->pictures => '',
                $tabeInfo->coverimage => '',
                $tabeInfo->type => 1,
                $tabeInfo->display => 1,
            );
        }
        $view->model = $modelDetail;
    }
}